﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

using VirtualTournaments.DataAccess.SqlServer.DataMappers;

namespace VirtualTournaments.DataAccess.SqlServer.DataProxies
{
	internal sealed class JourneyDataProxy : Business.Tournaments.Journey, IDataProxy<SqlServer.Journey>, Identifiable<SqlServer.Journey>
	{
		internal JourneyDataProxy(SqlServer.Journey dataObject)
		{
			InnerDataObject = dataObject;
			this.Matches = null; //TODO: esto está bastante fulero che!!!!
			this.Number = dataObject.Number;
		}

		#region Override properties

		internal bool MatchesHasBeenRead { get; set; }
		protected override List<Business.Tournaments.Match> Matches
		{
			get
			{
				if (!MatchesHasBeenRead)
				{
					MatchesHasBeenRead = true;
					if (base.Matches == null)
					{
						base.Matches = MapMatches();
					}
				}
				return base.Matches;
			}
		}

		#endregion

		#region Mapping methods

		private List<Business.Tournaments.Match> MapMatches()
		{
			return InnerDataObject.JourneyMatches.Select(journeyMatch => MatchesDataMapper.Instance.DataObject2BusinessObject(journeyMatch.Match)).ToList();
		}

		#endregion

		#region IDataProxy<Journey> Members

		public SqlServer.Journey InnerDataObject { get; set; }

		#endregion

		#region Identifiable<Journey> Members

		public Expression<Func<SqlServer.Journey, bool>> GetUniqueWhereExpression()
		{
			return journey => journey.JourneyId == InnerDataObject.JourneyId;
		}

		#endregion
	}
}
